<template>
    <div class="cascade-input">
        <template v-if="value.length > 0" v-for="(v, i) in value" :key="i">
            <div style="width: 100%;margin-bottom: 10px;">
                <div class="cascade-indicate" v-show="v.children">
                    <el-icon>
                        <CaretRight @click="changeExpand(i)" v-if="!v.expand" />
                        <CaretBottom @click="changeExpand(i)" v-else />
                    </el-icon>
                </div>
                <div class="cascade-indicate" v-show="!v.children"></div>
                <el-input v-model="v.field" @change="(value) => onChange(value, 'field', i)" style="width: calc(40%);"
                    max="10" maxlength="10" show-word-limit placeholder="自定义字段" />
                <span style=" display: inline-block; width: 20px; text-align: center;">--</span>
                <el-input v-model="v.keys" @change="(value) => onChange(value, 'keys', i)" style="width: calc(40%);"
                    max="30" maxlength="30" show-word-limit placeholder="字段值" />

                <el-button type="primary" link :icon="Plus" @click="addChildren(i)">新增子节点</el-button>
                <el-button type="danger" :icon="Delete" @click="delNode(i)" circle />
            </div>
            <template v-if="v.expand">
                <cascade-input style="width: calc(100% - 20px); margin-left: 20px;" v-if="v.children"
                    :value="v.children"></cascade-input>
            </template>
        </template>

    </div>
</template>
<script>
import { Delete, Plus } from '@element-plus/icons-vue'
export default {
    name: "cascadeInput",
    data() {
        return {
            Delete,
            Plus
        }
    },
    props: {
        value: {
            type: Array,
            default: () => [],
        },
    },
    methods: {
        onChangeField(value, key, i) {
            const list = this.value
            list[i][key] = value
            this.$emit("update:value", list);
        },
        addChildren(i) {
            const list = this.value
            if (list[i].children) {
                list[i].children.push({
                    field: '',
                    keys: '',
                    expand: true
                })
            } else {
                list[i].children = [{
                    field: '',
                    keys: '',
                    expand: true
                }]
            }
            this.$emit("update:value", list);
        },
        delNode(i) {
            const list = this.value
            list.splice(i, 1)
            this.$emit("update:value", list);

        },
        changeExpand(i) {
            const list = this.value
            list[i].expand = !list[i].expand
            this.$emit("update:value", list);
        }
    }
}
</script>

<style lang="scss" scoped>
.cascade-input {
    width: 100%;

    .cascade-indicate {
        display: inline-block;
        width: 20px;
        height: 20px;
    }
}
</style>